#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>

#define DEFAULT_PORT 7000
#define MULTICAST_ADDRESS "239.255.255.250"

uv_udp_t send_socket;
uv_udp_send_t send_req;
uv_buf_t discover_msg;
struct sockaddr_in multicast_addr;
std::size_t msg_num = 0;

void on_send(uv_udp_send_t *req, int status);

void send_message(uv_timer_t* handle) {
    std::string message = "aaaaa, " + std::to_string(++msg_num) + '\0';
    discover_msg = uv_buf_init(message.data(), message.length());
    uv_udp_send(&send_req, &send_socket, &discover_msg, 1, (const struct sockaddr*)&multicast_addr, on_send);
    message.clear();
}

void on_send(uv_udp_send_t *req, int status) {
    if (status) {
        fprintf(stderr, "Send error %s\n", uv_strerror(status));
        return;
    }
}

int main() {
    uv_loop_t *loop = uv_default_loop();

    uv_udp_init(loop, &send_socket);

    struct sockaddr_in send_addr;
    uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &send_addr);
    uv_udp_bind(&send_socket, (const struct sockaddr *)&send_addr, UV_UDP_REUSEADDR);

    
    uv_ip4_addr(MULTICAST_ADDRESS, DEFAULT_PORT, &multicast_addr);

    // uv_udp_set_broadcast(&send_socket, 1);

    // Create a timer to send messages every second
    uv_timer_t timer_req;
    uv_timer_init(loop, &timer_req);
    uv_timer_start(&timer_req, send_message, 1000, 1000);  // 1000ms interval

    return uv_run(loop, UV_RUN_DEFAULT);
}
